import { getLocale, history } from 'umi'; // eslint-disable-line
import {
  request, // eslint-disable-line
  getToken,
  getRawToken,
  setToken,
  removeToken,
  setDict,
  setAuthorities,
} from '@/zero';

const CURRENT_USER = {
  id: 1,
  username: 'admin',
  password: '1122-aabb',
  name: '深思君',
  phone: '15002435273',
  email: '417891235@qq.com',
};

/**
 * 初始结构
 */
const initialState = {
  currentUser: {}, // 当前用户
  collapsed: false, // 是否收起侧边栏
};

export default {
  namespace: 'global',

  state: initialState,

  effects: {
    /**
     * 获取当前用户信息
     */
    *setCurrentUser(_, { put }) {
      if (getToken() === '22d4d8143f9b463d946f83fb766be669') {
        yield put({
          type: 'save',
          payload: {
            currentUser: {
              ...CURRENT_USER,
              logo: '/images/logo.png',
              company: {
                passwordValidityPeriod: 30,
                accountLockNumber: 10,
                passwordNumber: 8,
                passwordStrength: 'uppercase,lowercase',
                sessionTimeout: 1,
              },
              security: {},
            },
          },
        });
      }
    },

    /**
     * 用户登录 => 账号登录
     */
    *userLogin({ payload }, { put }) {
      if (
        CURRENT_USER.username === payload.username &&
        CURRENT_USER.password === payload.password
      ) {
        setToken('22d4d8143f9b463d946f83fb766be669'); // 设置“Token” => 后端服务

        setAuthorities(['000', '001', '002', '003', '100', '101', '102', '103']);

        return {
          success: true,
          data: {
            firstLogin: 0,
            isPasswordExpire: 0,
          },
        };
      }

      yield put.resolve({
        type: 'setDict',
      });

      return {
        success: false,
        data: {
          message: '账号或密码错误',
        },
      };
    },

    *ssoLogin({ payload }, { put }) {
      setToken(`${payload.token}##${payload.main}##SSO`);
      setAuthorities([]);
      yield put.resolve({
        type: 'setCurrentUser',
      });
      yield put.resolve({
        type: 'setDict',
      });
    },

    /**
     * 退出登录
     */
    *userLogout(_, { put }) {
      const rawToken = getRawToken();

      removeToken(); // 移除“Token”
      setAuthorities([]);
      yield put({ type: 'save', payload: { currentUser: {} } }); // 清空登录信息

      if (rawToken?.endsWith('SSO')) {
        window.location.href =
          rawToken.split('##')[1] || 'https://cloud-dev.dip-aitech.com/product-list';
      } else {
        history.push('/g/login');
      }
    },

    /**
     * 获取数据字典
     */
    *setDict({ payload }) {
      console.log(`setDict`, payload);
      setDict();
    },

    *setCollapsed({ payload }, { put }) {
      return yield put({ type: 'save', payload });
    },

    *resetPassword({ payload }) {
      console.log(`resetPassword`, payload);
      return {
        success: true,
      };
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },

  subscriptions: {
    setup(params) {
      // Subscribe history(url) change, trigger `load` action if pathname is `/`
      return params.history.listen(({ pathname, search }) => {
        if (typeof window.ga !== 'undefined') {
          window.ga('send', 'pageview', pathname + search);
        }
      });
    },
  },
};
